//
//  WDGroMoreNativeManager.m
//  WDGroMore
//
//  Created by YeJary on 2025/5/19.
//

//
//  WDGroMoreNativeManager.m
//  WDGroMore
//

#import "WDGroMoreNativeManager.h"
#import "WDGroMoreDelegateManager.h"
#import "WDGroMoreHeader.h"
#import <BUAdSDK/BUNativeAd.h>
#import "WDBMS.h"
@interface WDGroMoreNativeManager ()<BUMNativeAdsManagerDelegate, BUMNativeAdDelegate, BUCustomEventProtocol>

@property (nonatomic, strong) BUNativeAdsManager *nativeAdManager;
@property (nonatomic, copy) NSString *userUUId;
@property (nonatomic, assign) BOOL shouldShowAd;
@property (nonatomic, strong) NSArray<BUNativeAd *> *nativeAds;
@property (nonatomic, strong) UIView *nativeAdContainer;

@end

@implementation WDGroMoreNativeManager

+ (instancetype)manager {
    static WDGroMoreNativeManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[WDGroMoreNativeManager alloc] init];
    });
    return instance;
}

- (void)loadNativeAdWithPlacementId:(NSString *)placementId userId:(NSString *)userId {
    NSLog(@"[NativeAd] 开始加载原生广告 placementId: %@", placementId);
    if (self.nativeAdManager) {
        [self.nativeAdManager.mediation destory];
        NSLog(@"[NativeAd] 清理旧的 nativeAdManager 实例");
    }

    BUAdSlot *slot = [[BUAdSlot alloc] init];
    slot.ID = placementId;
    slot.AdType = BUAdSlotAdTypeFeed;
    slot.position = BUAdSlotPositionFeed;
    slot.mediation.mutedIfCan = YES;
    slot.adSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 400);
    slot.imgSize = [BUSize sizeBy:BUProposalSize_Feed690_388];

    self.nativeAdManager = [[BUNativeAdsManager alloc] initWithSlot:slot];
    self.nativeAdManager.mediation.rootViewController = UIApplication.sharedApplication.keyWindow.rootViewController;
    self.nativeAdManager.delegate = self;
    [self.nativeAdManager loadAdDataWithCount:3];

    [WDGroMoreTrackManager track:BMS_EVENT_AD_REQUEST
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_REQUEST,
                                   BMS_PARAM_TAB1:@"",
                                   BMS_PARAM_TAB2:placementId ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_REQUEST
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
}

+ (void)showNativeAd {
    [self showNativeAdAtPosition:0 yOffset:0];
}

+ (void)showNativeAdAtPosition:(NSInteger)position yOffset:(CGFloat)yOffset {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    CGFloat scale = UIScreen.mainScreen.bounds.size.height / 1334.0;
    CGFloat offsetY = yOffset * scale;

    CGRect frame = CGRectMake(0,
                              (position == 0 ? window.bounds.size.height - 300 - offsetY : offsetY),
                              window.bounds.size.width,
                              300);

    WDGroMoreNativeManager *sdk = [WDGroMoreNativeManager manager];
    if (sdk.nativeAds.count == 0) {
        NSLog(@"[NativeAd] 没有可展示的原生广告");
        return;
    }

    BUNativeAd *nativeAd = sdk.nativeAds.firstObject;
    nativeAd.rootViewController = window.rootViewController;
    nativeAd.delegate = sdk;

    sdk.nativeAdContainer = [[UIView alloc] initWithFrame:frame];
    sdk.nativeAdContainer.backgroundColor = UIColor.whiteColor;
    [window addSubview:sdk.nativeAdContainer];

    if (nativeAd.mediation.isExpressAd) {
        NSLog(@"[NativeAd] 使用模板渲染");
        [nativeAd.mediation render];
        UIView *adView = nativeAd.mediation.canvasView;
        adView.frame = sdk.nativeAdContainer.bounds;
        [sdk.nativeAdContainer addSubview:adView];
        if ([WDGroMoreDelegateManager manager].delegate &&
            [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreNativeAdDidShow:)]) {
            [[WDGroMoreDelegateManager manager].delegate WDGroMoreNativeAdDidShow:nativeAd];
        }
    } else {
        NSLog(@"[NativeAd] 自渲染原生广告");
    }
}

+ (void)removeNativeAd {
    NSLog(@"[NativeAd] 移除原生广告视图");
    WDGroMoreNativeManager *sdk = [WDGroMoreNativeManager manager];
    [sdk.nativeAdContainer removeFromSuperview];
    sdk.nativeAdContainer = nil;
}

#pragma mark - BUMNativeAdsManagerDelegate

- (void)nativeAdsManagerSuccessToLoad:(BUNativeAdsManager *)adsManager nativeAds:(NSArray<BUNativeAd *> *)nativeAdDataArray {
    NSLog(@"✅ [NativeAd] 成功加载原生广告数量: %lu", (unsigned long)nativeAdDataArray.count);
    self.nativeAds = nativeAdDataArray;

    for (BUNativeAd *ad in nativeAdDataArray) {
        NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:ad];
        NSString *adn = ritInfo[@"adn"];
        NSString *ecpm = ritInfo[@"ecpm"];
        NSString *slotID = ritInfo[@"slotID"];

        [WDGroMoreTrackManager track:BMS_EVENT_AD_FILL
                              params:@{BMS_PARAM_WDS:BMS_WDS_AD_FILL,
                                       BMS_PARAM_TAB1:adn ?: @"",
                                       BMS_PARAM_TAB2:slotID ?: @"",
                                       BMS_PARAM_TAB3:ecpm ?: @""}
                               dType:BMS_DTYPE_AD_ACTION
                                desc:BMS_WDS_AD_FILL
                             options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
        ad.delegate = self;
        ad.rootViewController = UIApplication.sharedApplication.keyWindow.rootViewController;

        if (ad.mediation.isExpressAd) {
            NSLog(@"[NativeAd] 模板广告开始渲染");
            [ad.mediation render];
        }
    }
}

- (void)nativeAdsManager:(BUNativeAdsManager *)adsManager didFailWithError:(NSError *)error {
    NSLog(@"❌ [NativeAd] 加载失败: %@", error.localizedDescription);
}

#pragma mark - BUMNativeAdDelegate

- (void)nativeAdDidClick:(BUNativeAd *)nativeAd withView:(UIView *)view {
    NSLog(@"👉 [NativeAd] 点击广告");
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:nativeAd];
    NSString *adn = ritInfo[@"adn"];
    NSString *ecpm = ritInfo[@"ecpm"];
    NSString *slotID = ritInfo[@"slotID"];

    [WDGroMoreTrackManager track:BMS_EVENT_AD_CLICK
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_CLICK,
                                   BMS_PARAM_TAB1:adn ?: @"",
                                   BMS_PARAM_TAB2:slotID ?: @"",
                                   BMS_PARAM_TAB3:ecpm ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_CLICK
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
}

- (void)nativeAd:(BUNativeAd *)nativeAd dislikeWithReason:(NSArray<BUDislikeWords *> *)filterWords {
    NSLog(@"[NativeAd] 用户点击关闭广告");
    [self.class removeNativeAd];
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreNativeAdDidClose:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreNativeAdDidClose:nativeAd];
    }
}

- (void)nativeAdExpressViewRenderFail:(BUNativeAd *)nativeAd error:(NSError * _Nullable)error {
    NSLog(@"❌ [NativeAd] 模板渲染失败: %@", error.localizedDescription);
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreNativeAdDidShowFailed:error::)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreNativeAdDidShowFailed:nativeAd error:error];
    }
}

- (void)nativeAdExpressViewRenderSuccess:(BUNativeAd *)nativeAd {
    NSLog(@"✅ [NativeAd] 模板渲染成功");
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:nativeAd];
    NSString *adn = ritInfo[@"adn"];
    NSString *ecpm = ritInfo[@"ecpm"];
    NSString *slotID = ritInfo[@"slotID"];

    [WDGroMoreTrackManager track:BMS_EVENT_AD_IMPRESSION
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_SHOW,
                                   BMS_PARAM_TAB1:adn ?: @"",
                                   BMS_PARAM_TAB2:slotID ?: @"",
                                   BMS_PARAM_TAB3:ecpm ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_SHOW
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
    
}

- (void)nativeAdShakeViewDidDismiss:(BUNativeAd *)nativeAd {
    NSLog(@"[NativeAd] ShakeView 已关闭");
}

- (void)nativeAdVideo:(BUNativeAd *)nativeAdView rewardDidCountDown:(NSInteger)countDown {
    NSLog(@"[NativeAd] 视频倒计时: %ld", (long)countDown);
}

- (void)nativeAdVideo:(BUNativeAd *)nativeAd stateDidChanged:(BUPlayerPlayState)playerState {
    NSLog(@"[NativeAd] 视频播放状态变化: %ld", (long)playerState);
}

- (void)nativeAdVideoDidClick:(BUNativeAd *)nativeAd {
    NSLog(@"[NativeAd] 视频点击");
}

- (void)nativeAdVideoDidPlayFinish:(BUNativeAd *)nativeAd {
    NSLog(@"[NativeAd] 视频播放完成");
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:nativeAd];
    NSString *adn = ritInfo[@"adn"];
    NSString *ecpm = ritInfo[@"ecpm"];
    NSString *slotID = ritInfo[@"slotID"];

    [WDGroMoreTrackManager track:BMS_EVENT_AD_IMPRESSION_DONE
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_FINISH,
                                   BMS_PARAM_TAB1:adn ?: @"",
                                   BMS_PARAM_TAB2:slotID ?: @"",
                                   BMS_PARAM_TAB3:ecpm ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_FINISH
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
}

- (void)nativeAdWillPresentFullScreenModal:(BUNativeAd *)nativeAd {
    NSLog(@"[NativeAd] 即将展示全屏广告页");
}

@end
